package com.ayf.payment.game.api.filter;

import com.ayf.payment.game.api.auths.AbstractAuthorization;
import com.ayf.payment.game.api.auths.OAuthAuthorization;
import com.ayf.payment.game.api.bean.AuthorizationInfo;
import com.ayf.payment.game.api.bean.WrapperHttpServletRequest;
import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.dto.player.PlayerLoginToken;
import com.ayf.payment.game.api.exception.AuthorizeFailedException;
import com.ayf.payment.game.api.type.AuthorizationType;
import com.ayf.payment.game.api.utils.MapUtil;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@WebFilter(urlPatterns = "/p/*", filterName = "authorizationPlayerFilter")
public class AuthorizationPlayerFilter extends BasicPlayerFilter implements Filter {

    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private OAuthAuthorization oAuthAuthorization;
    @Resource
    private AbstractAuthorization abstractAuthorization;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    /**
     * 处理授权
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        WrapperHttpServletRequest reqWrapper = new WrapperHttpServletRequest(req);
//        LogPortal.info("{} url:[{}] ", this.getClass().getName(), req.getRequestURI());
        //需要校验的请求
        if (!isContain(req.getRequestURI(), canAlwaysVisits)) {
            try {
                //获取实例
                AbstractAuthorization authorization = abstractAuthorization.getInstanceByAuthType(req);
                //签名校验
                AuthorizationInfo authorizationInfo = authorization.execute(reqWrapper);
                reqWrapper.setPrincipal(authorizationInfo);
            } catch (Exception e) {
                handleException(res, e);
                return;
            }
        }

        AuthorizationInfo authorizationInfo = (AuthorizationInfo) reqWrapper.getUserPrincipal();
        if (authorizationInfo != null) {
            //设置Customer信息
            PlayerLoginToken token = null;
            try {
                if (authorizationInfo.getAuthType() == AuthorizationType.OAUTH) {//需要校验Token
                    if (StringUtils.isBlank(authorizationInfo.getAuthValue())) {
                        throw new AuthorizeFailedException("accessToken cannot be null");
                    }
                    token = redisCacheUtil.getObjectFromCache(authorizationInfo.getAuthValue());
                    if (null == token) {
                        throw new AuthorizeFailedException("Authorization failed, please login again");
                    }
                }
            } catch (AuthorizeFailedException e) {
                handleException(res, e);
                return;
            }
            reqWrapper.setPrincipal(token);
        }
        chain.doFilter(reqWrapper, res);
    }

    @Override
    public void destroy() {

    }
}
